package game.players.user;

import game.ball.Possessed;
import game.ball.SoccerBall;
import game.players.SoccerPlayer;
import game.players.SoccerPlayerCPU;
import game.players.states.WithoutBall;
import game.players.user.movements.WithBallStationaryUser;
import game.players.user.running.WithoutBallStationaryRunningUser;
import game.scene.MatchScene;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.colissions.CollisionDetector;
import com.uqbar.vainilla.events.constants.Key;

public abstract class WithoutBallUser extends WithoutBall {
	
	private int timer = 5;
	
	public WithoutBallUser(SoccerPlayer player) {
		super(player);
	}

	public void update(DeltaState deltaState) {
		
		//Evita la colisión inmediata
		if (this.timer <= 0)
			super.update(deltaState);
		else
			this.timer--;
		
		//cambio de jugador
		if (deltaState.isKeyPressed(Key.C) && this.timer < 4) {
			MatchScene scene = this.getPlayer().getScene();
			SoccerPlayerCPU closerBallPlayer = scene.getCloserBallTeammate(this.getPlayer());
			this.getPlayer().getScene().changeFromUserToCPU(this.getPlayer(), closerBallPlayer);
		}
		
		//quitar la pelota a un rival
		if (deltaState.isKeyPressed(Key.Z))
			this.getPlayer().setState(new WithoutBallSweepingUserPlayer(this.getPlayer(), this.getPlayer().isInRightDirection()));
		
		//Aumenta la velocidad del jugador
		if (deltaState.isKeyBeingHold(Key.SHIFT))
			this.getPlayer().setState(new WithoutBallStationaryRunningUser(this.getPlayer()));
	}

	public void takePossession(SoccerBall ball) {
		double advanceX = this.getPlayer().getX() + this.getPlayer().getAppearance().getWidth() - ball.getX() - ball.getRatio();
		double advanceY = this.getPlayer().getY() + this.getPlayer().getAppearance().getHeight() - ball.getY() - ball.getRatio();
		
		ball.moveNormally(advanceX, advanceY);
		
		this.getPlayer().setState(new WithBallStationaryUser(this.getPlayer()));
		ball.setState(new Possessed(this.getPlayer()));
	}
	
	public boolean collidesAgainstBall(SoccerBall ball, SoccerPlayer player) {
		return CollisionDetector.INSTANCE.collidesCircleAgainstRect(
			ball.getX(), ball.getY(), ball.getRatio(),
			player.getX() + player.getAppearance().getWidth() - player.getFeetWidth(), 
			player.getY() + player.getAppearance().getHeight() - player.getFeetHeight(), 
			player.getFeetWidth(), player.getFeetHeight()
			);
	}


}
